package com.cc.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {
//    private  static  SqlSession  sqlSession=null;
    //线程安全的问题（https://www.bilibili.com/read/cv9258735/）
   private static ThreadLocal<SqlSession> tlLocal = new ThreadLocal<SqlSession>();

    static {
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //将sqlSession与当前线程绑定的ThreadLocal中
            tlLocal.set(sqlSession);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession openSession() {
        return tlLocal.get();
    }
    
}